<template>
	<section>
		<!--工具条-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true">
        <el-form-item>
          <el-input v-model="keyword" placeholder="部门/部门编号"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" v-on:click="getDepartments">查询</el-button>
        </el-form-item>
        <el-form-item>
          <!--v-perm="'menu:add'"-->
          <el-button type="primary" v-perm="'department/addAndEdit'" @click="handleAdd">新增</el-button>
        </el-form-item>
      </el-form>
    </el-col>
		<!--列表-->
		<el-table :data="Departments" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
			<el-table-column type="selection" width="55">
			</el-table-column>
			<el-table-column type="index" width="60">
			</el-table-column>
      <el-table-column prop="id" label="ID" width="120" sortable>
      </el-table-column>
			<el-table-column prop="sn" label="编号" width="120" sortable>
			</el-table-column>
      <el-table-column prop="name" label="部门" width="120" sortable>
			</el-table-column>
			<el-table-column prop="dirPath" label="路径" width="100" sortable>
			</el-table-column>
			<el-table-column prop="state" label="部门状态" width="100" sortable>
        <template slot-scope="scope">
          <span style="color: green" v-if="scope.row.state === 1">正常</span>
          <span style="color: red" v-else-if="scope.row.state === 0">停用</span>
          <span style="color: darkslategray" v-else>未知</span>
        </template>
      </el-table-column>
      <!-- 部门经理列 -->
      <el-table-column prop="manager.username" label="部门经理" width="120" sortable>
      </el-table-column>
      <!-- 上级部门列 -->
      <el-table-column prop="parent.name" label="上级部门" min-width="180" sortable>
      </el-table-column>
      <!-- 操作列 -->
      <el-table-column label="操作" width="150">
        <template slot-scope="scope">
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
        </template>
			</el-table-column>
		</el-table>


    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
      <el-pagination layout="prev, pager, next"
                     @current-change="handleCurrentChange"
                     :page-size="pageSize"
                     :total="total"
                     :current-page="currentPage"
                     style="float:right;">
      </el-pagination>
    </el-col>

    <!--编辑界面-->
    <el-dialog :title="title" :visible.sync="editFormVisible"  :close-on-click-modal="false">
      <el-form :model="editForm" label-width="80px" :rules="editFormRules" ref="editForm">

        <el-form-item label="部门名字" prop="name">
          <el-input v-model="editForm.name" auto-complete="off"></el-input>
        </el-form-item>

        <el-form-item label="部门编号" prop="sn">
          <el-input v-model="editForm.sn" auto-complete="off"></el-input>
        </el-form-item>

        <el-form-item label="启用状态">
          <el-radio-group v-model="editForm.state">
            <el-radio class="radio" :label="1">启用</el-radio>
            <el-radio class="radio" :label="0">停用</el-radio>
          </el-radio-group>
        </el-form-item>


        <el-form-item label="部门经理">

          <el-select v-model="editForm.manager" value-key="id" placeholder="请选择" clearable>
            <el-option v-for="item in managers"
                       :label="item.username"
                       :value="item">
              <span style="float: left">{{ item.username }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.phone }}
            </span>
            </el-option>

          </el-select>
        </el-form-item>



        <el-form-item label="上级部门">
          <el-cascader v-model="editForm.parent_id"
                       :options="deptTree"
                       :props="{
                                  checkStrictly: true,
                                  label: 'name', // 级联框显示那个属性的值
                                  value: 'id'    // 回显时需要,回传值的时候也需要
                             }"
                       clearable>
          </el-cascader>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="editFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="editSubmit" :loading="editLoading">提交</el-button>
      </div>
    </el-dialog>


	</section>
</template>

<script>


	export default {
		data() {
			return {
			  /*1.分页数据查询参数*/
        total: 0,
        currentPage: 1,
        pageSize:5,
			  /*2.部门分页数据*/
        Departments: [],
        /*6. 编辑框标题绑定*/
        title:"",

        /*高级查询keyword*/
        keyword:"",
        /*8.多个员工对象*/
        managers:[],
        /*10.部门树结构数据*/
        deptTree:[],
				listLoading: false,
				sels: [],//列表选中列

				editFormVisible: false,//编辑界面是否显示
				editLoading: false,
				editFormRules: {
					name: [
						{ required: true, message: '请输入姓名', trigger: 'blur' }
					],
          sn: [
            { required: true, message: '请输入编号', trigger: 'blur' }
          ]
				},
				//编辑界面数据
				editForm: {
          parent_id:null
				},
			}
		},
		methods: {
		  /*1.获取部门列表*/
      getDepartments() {

        let para = {
          currentPage: this.currentPage,
          pageSize:this.pageSize,
          keyword :this.keyword
        };
        this.listLoading = true;
        //then删除数据  请求响应没有问题，级便数据没有删除成功，走then       catch请求异常404  400 500
        this.$http.post("/department",para).then(result=>{
          let {totals,data} = result.data;
          this.total = totals;
          this.Departments = data
          this.listLoading = false;
        }).catch(result=>{

        })

      },
      /*2.页数改变获取分页数据函数*/
      handleCurrentChange(val) {
        this.currentPage = val;
        this.getDepartments();
      },

      /*3.根据ID删除*/
      handleDel: function (index, row) {
        this.$confirm('确认删除该记录吗?', '提示', {
          type: 'warning'
        }).then(() => {
          this.listLoading = true;
          //result   AjaxResult
          this.$http.delete("/department/"+row.id).then(result=>{
            let {success,message} = result.data;
            if(success){  //请求业务是否成功
              this.$message({
                message: message,
                type: 'success'
              });
              /*成功删除之后：   当前页删除完毕，方案   1. 删完第5页，退回第4页查询4页得数据    2. 删完第5页，停留第5页，数据查询为空*/
              //21
              if( (this.total-1)%this.pageSize==0 ){//说明已经是在删除当前页得最后一条： 当前页减一之后在查询
                this.currentPage -=1;
              }
              this.getDepartments();
            }else{
              this.$message({
                message: message,
                type: 'error'
              });
            }
            this.listLoading = false;
          }).catch(result=>{  //404 500 400 请求失败

          })
        }).catch(() => {

        });
      },
			//性别显示转换
			formatSex: function (row, column) {
				return row.sex == 1 ? '男' : row.sex == 0 ? '女' : '未知';
			},

      /*4.批量删除*/
      batchRemove: function () {
        //[{id:1,name:xx},id:2,name:xx},id:3,name:xx}]   [1,2,3]   "[1,2,3]"
        var ids = this.sels.map(item => item.id)  //[1,2,3]
        this.$confirm('确认删除选中记录吗？', '提示', {
          type: 'warning'
        }).then(() => {
          this.listLoading = true;
          this.$http.patch("/department",ids).then(result=>{
            let {success,message} = result.data
            if(success){
              this.$message({
                message: message,
                type: 'success'
              });
              if((this.total-ids.length)%this.pageSize==0){
                this.currentPage-=1;
              }
              this.getDepartments()
            }else{
              this.$message({
                message: message,
                type: 'error'
              });
            }
            this.listLoading = false;
          }).catch(result=>{

          })
        }).catch(() => {

        });
      },
      /*5.表格选项改变触发事件*/
      selsChange: function (sels) {
        this.sels = sels;
      },

      /*6 新增:  显示编辑界面*/
      handleAdd: function () {
        this.getEmpManagers();
        this.getDeptTree()
        this.editFormVisible = true;
        this.title = "新增"
        this.editForm= {
          sn: "",
          name: "",
          state: 1,
          manager_id: null,
          manager: {},
          parent_id: null,
          parent: {}
        }
      },
      /*7.修改：显示编辑界面*/
      handleEdit: function (index, row) {
        this.getEmpManagers();
        this.getDeptTree()
        this.title = "编辑"
        this.editFormVisible = true;
        this.editForm = Object.assign({}, row);  //拷贝row给到editForm
        //this.editForm = row;  //拷贝row给到editForm
        console.log("row",row)
      },
      /*8.添加和修改，提交数据*/
      editSubmit: function () {
        this.$refs.editForm.validate((valid) => {
          if (valid) {
            this.$confirm('确认提交吗？', '提示', {}).then(() => {
              this.editLoading = true;
              let department = Object.assign({}, this.editForm);
              let parent_id = department.parent_id
              if(parent_id!=null && parent_id.length>0)  department.parent_id = parent_id[parent_id.length-1]
              if(parent_id!=null && parent_id.length==0) department.parent_id = null
              this.$http.put("/department",department).then(result=>{
                this.editLoading = false;
                this.editFormVisible = false;
                let {success,message} = result.data;
                if(success){
                  this.$message({type:"success",message:message})
                  this.getDepartments();
                }else{
                  this.$message({type:"error",message:message})
                }
              }).catch(result=>{

              })
            });
          }
        });
      },
      /*9.部门经理查询*/
      getEmpManagers(){
        this.$http.get("/employee").then(result=>{
          this.managers = result.data
        }).catch(result=>{})
      },
      /*9.部门经理查询*/
      getDeptTree(){
        this.$http.get("/department/tree").then(result=>{
          this.deptTree= result.data
        }).catch(result=>{})
      },


		},
		mounted() {

			this.getDepartments();
		}
	}

</script>

<style scoped>

</style>